package com.fh.user.service.impl;/**
 * 描述:
 * Author:袁亚强
 * Date:2021/12/911:13
 */

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fh.common.baseData.CommonData;
import com.fh.common.exceptions.ParamException;
import com.fh.common.exceptions.PasswordException;
import com.fh.common.exceptions.UserNoException;
import com.fh.user.entity.vo.User;
import com.fh.user.mapper.UserMapper;
import com.fh.user.service.UserService;
import com.fh.utils.EmailThread;
import com.fh.utils.EmailUtils;
import com.fh.utils.JWT;
import com.fh.utils.yyqMD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * created by macro on 2021/12/9,
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private JavaMailSender mailSender;//一定要用@Autowired

    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public Integer sendMimeMail(String email) {
        HttpSession session = request.getSession();
        //验证参数是否正确
        String regEx1 = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        boolean matches = email.matches(regEx1);
        if(!matches){
            throw new ParamException();
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("email", email);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            return 0;
        }
        //验证是否已经发过验证码
        Object o = redisTemplate.opsForValue().get("code"+ CommonData.REDIS_PRO);
        if(o!=null){
            return 2;
        }
       /* try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();

            mailMessage.setSubject("验证码邮件");//主题
            //生成随机数
            String code = randomCode();

            //将随机数放置到redis中
            redisTemplate.opsForValue().set("email"+ CommonData.REDIS_PRO,email,120, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set("code"+ CommonData.REDIS_PRO,code,120, TimeUnit.SECONDS);

            mailMessage.setText("您收到的验证码是："+"<p color='red'>"+code+"</p>"+"<br>"+"验证码5分钟之内有效!");//内容

            mailMessage.setTo(email);//发给谁

            mailMessage.setFrom("3168442947@qq.com");//你自己的邮箱

            mailSender.send(mailMessage);//发送
            return 1;
        }catch (Exception e){
            e.printStackTrace();
            return 3;
        }*/
        //生成一个随机的验证码
        String code = randomCode();
        System.out.println(code);
        //发送邮箱

        EmailThread emailThread=new EmailThread(email, "飞狐软件","你的验证码为：<font color='red'>"+code+"</font>");
        emailThread.start();
        //记录到服务器中  下次验证验证码  60秒内有效
        redisTemplate.opsForValue().set("email"+ CommonData.REDIS_PRO,email,120, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set("code"+ CommonData.REDIS_PRO,code,120, TimeUnit.SECONDS);
        return 1;
    }



    /**
     * 随机生成6位数的验证码
     * @return String code
     */
    public String randomCode(){
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }


    @Override
    public Integer validatecode(String email, String code) {
        String emailData = (String) redisTemplate.opsForValue().get("email"+ CommonData.REDIS_PRO);
        String codeData = (String) redisTemplate.opsForValue().get("code"+ CommonData.REDIS_PRO);

        if (emailData == null || emailData.isEmpty()){
            //return "error,请重新验证";
            return 0;
        }

        if(!emailData.equals(email)){
            return 0;
        }

        //如果email数据为空，或者不一致，验证失败
        if (codeData == null || codeData.isEmpty()){
            //return "error,请重新验证";
            return 2;
        }else if (!codeData.equals(code)){
            //return "error,请重新验证";
            return 0;
        }
        return 1;
    }

    @Override
    public Integer addUser(User user) {
        if (StringUtils.isEmpty(user.getName())){
            throw new ParamException();
        }
        if (StringUtils.isEmpty(user.getPassword())){
            throw new ParamException();
        }
        if (StringUtils.isEmpty(user.getEmail())){
            throw new ParamException();
        }

        QueryWrapper q = new QueryWrapper();
        q.eq("name", user.getName());
        User userName = userMapper.selectOne(q);
        if (userName!=null){
            return 0; //0 账号存在
        }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("email", user.getEmail());
        User email = userMapper.selectOne(queryWrapper);
        if (email!=null){
            return 2; //2 邮箱已存在存在
        }


        User u = new User();
        u.setName(user.getName());
        u.setCreateDate(new Date());
        u.setPassword(yyqMD5.yyqMD5(yyqMD5.yyqMD5(user.getPassword())+user.getName()));
        u.setEmail(user.getEmail());
        u.setIphone(user.getIphone());
        userMapper.insert(u);
       /* try {
            EmailUtils.sendMail(user.getEmail(),"欢迎"+user.getName(),"恭喜您注册成功!<br>你的账号为:<font color='red'>"+user.getName()+"</font><br>你的密码为:<font color='red'>"+user.getPassword()+"</font>");
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        EmailThread emailThread = new EmailThread(user.getEmail(), "欢迎" + user.getName(), "恭喜您注册成功!<br>你的账号为:<font color='red'>" + user.getName() + "</font><br>你的密码为:<font color='red'>" + user.getPassword() + "</font>");
        emailThread.start();
        redisTemplate.delete("email" + CommonData.REDIS_PRO);
        redisTemplate.delete("code"+ CommonData.REDIS_PRO);
        return 1;
    }

    @Override
    public String login(String name, String password) {
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
            throw new ParamException();
        }
        QueryWrapper q = new QueryWrapper();
        q.eq("name", name);
        User user = userMapper.selectOne(q);
        if (StringUtils.isEmpty(user)) {
            throw new UserNoException("用户不存在");
        }
        String s = yyqMD5.yyqMD5(yyqMD5.yyqMD5(password) + name);
        if (!user.getPassword().equals(s)) {
            throw new PasswordException("密码错误");
        }

        String sign = JWT.sign(user, 60 * 60 * 24);

        return sign;
    }

    @Override
    public List<User> queryUser() {
        return userMapper.selectList(null);
    }

    @Override
    public User queryToken(String token) {
        if (StringUtils.isEmpty(token)) {
            throw new ParamException();
        }
        return JWT.unsign(token, User.class);
    }

}
